package cn.kais.drawer.unit;

import cn.kais.drawer.menu.MenuCodeBarFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;


/**
 * 条形码
 * 'CODE128'   EncodeHintType.FORCE_CODE_SET = 空
 * 'CODE128B'  EncodeHintType.FORCE_CODE_SET = B
 * 'CODE11'
 * 'CODABAR'
 * 二维码
 * 'CODE16K'
 * 'CODE32'
 * 'CODE39'
 * 'CODABLOCKF'
 */
public class UnitCode {

    public static BufferedImage iCodeBuffer(MenuCodeBarFormat format, String content, int width, int height, Color mColor, Color bColor) {
        System.out.println("输入码宽度：" + width);
        System.out.println("输入码高度：" + height);

//        BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
//        Graphics2D sd = image.createGraphics();
//        sd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码方式
        hints.put(EncodeHintType.MARGIN, 0); // 白边

//        ErrorCorrectionLevel.L: 大约可以纠正7%的错误
//        ErrorCorrectionLevel.M: 大约可以纠正15%的错误（默认值）
//        ErrorCorrectionLevel.Q: 大约可以纠正25%的错误
//        ErrorCorrectionLevel.H: 大约可以纠正30%的错误
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 容错率

        //  下两个互斥
//        hints.put(EncodeHintType.CODE128_COMPACT, true);
//        if (format == MenuCodeBarFormat.CODE_128_B) {
//            hints.put(EncodeHintType.FORCE_CODE_SET, "B");
//        }


//        String utf8String = "Hello, 世界!"; // 包含非ASCII字符的UTF-8字符串
//        content = convertToASCII(utf8String);
//        System.out.println(content); // 将输出 "Hello,"
        System.out.println("码类型：" + format.code);
        BufferedImage ima = null;
        try {
            BitMatrix matrix = new MultiFormatWriter().encode(content, format.format, width, height, hints);
            // 去除二维码白边 format == MenuCodeBarFormat.AZTEC
            if (format == MenuCodeBarFormat.QR_CODE || format == MenuCodeBarFormat.DATA_MATRIX) {
                matrix = onRemoveWhiteBorder(matrix);
            }
            int mW = matrix.getWidth();
            int mH = matrix.getHeight();
            ima = new BufferedImage(mW, mH, BufferedImage.TYPE_INT_ARGB);
            // 自定义颜色
            for (int x = 0; x < mW; x++) {
                for (int y = 0; y < mH; y++) {
                    ima.setRGB(x, y, matrix.get(x, y) ? mColor.getRGB() : bColor.getRGB());
//                        if (format == BarcodeFormat.QR_CODE) {
//                            ima.setRGB(x, y, matrix.get(x, y) ? color.getRGB() : Color.white.getRGB());
//                        } else {
//                            ima.setRGB(x, y, matrix.get(x, y) ? Color.white.getRGB() : color.getRGB());
//                        }
                }
            }
//            if (true) { // 自定义颜色
//
//            } else {
//                ima = MatrixToImageWriter.toBufferedImage(matrix);
//            }
            return ima;
        } catch (WriterException e) {
            System.out.println("二维码/条形码生成失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除二维码白边
     */
    private static BitMatrix onRemoveWhiteBorder(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2];
        int resHeight = rec[3];

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }


//    private static void test() {
//        //        BarcodeFormat format = BarcodeFormat.QR_CODE;
//        BarcodeFormat format = BarcodeFormat.CODE_128;
//        int width = 101;  // 101x50 202x100 303x150 404x200 类推
//        int height = 50;
//        String content = "123456";
//        BufferedImage ima = iCodeBuffer(format, content, width, height);
//        try {
//            System.out.println("宽度：" + ima.getWidth());
//            System.out.println("高度：" + ima.getHeight());
//            ImageIO.write(ima, "png", new File("Code1.png"));
//        } catch (IOException e) {
//            System.out.println("文本流信息输出图片出错");
//            throw new RuntimeException(e);
//        }
//    }
//
//    public static void main(String[] args) {
//        test();
//    }


}
